package cn.lili.modules.member.serviceimpl;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.SnowFlake;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.goods.entity.dos.Goods;
import cn.lili.modules.member.entity.dos.RedPackTask;
import cn.lili.modules.member.entity.dos.RedPackUser;
import cn.lili.modules.member.entity.dos.RedPackUserTask;
import cn.lili.modules.member.mapper.RedPackTaskMapper;
import cn.lili.modules.member.service.*;
import cn.lili.modules.promotion.entity.enums.PromotionsStatusEnum;
import cn.lili.modules.system.client.GoodsAuthClient;
import cn.lili.modules.system.entity.dos.LiAuthSpaceGoods;
import cn.lili.mybatis.util.PageUtil;
import com.api.UserApi;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pojos.FyUser;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@AllArgsConstructor
@Slf4j
public class RedPackTaskServiceImpl extends ServiceImpl<RedPackTaskMapper, RedPackTask>
        implements RedPackTaskService {

    private final RedPackUserTaskService redPackUserTaskService;

    private final UserApi userApi;

    private final RedPackInviteHelpService redPackInviteHelpService;

    private final GoodsAuthClient goodsAuthClient;

    private final RedPackUserService redPackUserService;

    /**
     * 分页查询红包任务
     * @param redPackTask
     * @param page
     * @return
     */
    @Override
    public Page<RedPackTask> getByPage (RedPackTask redPackTask, PageVO page) {
        LambdaQueryWrapper<RedPackTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RedPackTask::getDeleteFlag, false);
        queryWrapper.eq(StringUtils.isNotEmpty(redPackTask.getTaskName()), RedPackTask::getTaskName, redPackTask.getTaskName());
        queryWrapper.eq(null != redPackTask.getStatus(), RedPackTask::getStatus, redPackTask.getStatus());
        queryWrapper.ge(null != redPackTask.getStartTime(), RedPackTask::getStartTime, redPackTask.getStartTime());
        queryWrapper.le(null != redPackTask.getEndTime(), RedPackTask::getEndTime, redPackTask.getEndTime());
        queryWrapper.orderByDesc(RedPackTask::getCreateTime);
        return this.baseMapper.selectPage(PageUtil.initPage(page), queryWrapper);
    }

    /**
     * 获取任务列表
     * @return
     */
    @Override
    public List<RedPackTask> getByList () {
        log.info("获取红包广场任务列表START");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LambdaQueryWrapper<RedPackTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RedPackTask::getStatus, PromotionsStatusEnum.START.name());
        queryWrapper.eq(RedPackTask::getDeleteFlag, false);
        List<RedPackTask> redPackTaskList = this.list(queryWrapper);
        log.info("获取红包广场任务列表SIZE：{}, {}", redPackTaskList.size(), UserContext.getCurrentId());
        if (!redPackTaskList.isEmpty()) {
            redPackTaskList.forEach(redPackTask -> {
                // 获取当天用户任务数据
                RedPackUserTask redPackUserTask = redPackUserTaskService.getTodayUserTask(redPackTask.getId());
                // 当天没有任务
                if (null == redPackUserTask) {
                    redPackUserTask = new RedPackUserTask();
                    redPackUserTask.setUserId(UserContext.getCurrentId());
                    redPackUserTask.setTaskId(redPackTask.getId());
                    redPackUserTask.setRedPackCount(0);
                    redPackUserTask.setOpenId(Objects.requireNonNull(UserContext.getCurrentUser()).getOpenId());
                    redPackUserTask.setStatus(0);
                    redPackUserTask.setId(SnowFlake.getIdStr());
                    redPackUserTaskService.save(redPackUserTask);
                    redPackTask.setTaskStatus(0);
                }
                // 是否邀新任务
                if (redPackTask.getTaskType() == 1) {
                    // 有任务，则获取飞语用户数据
                    List<FyUser> fyUserList = userApi.getTodayChildUserList(
                            Objects.requireNonNull(UserContext.getCurrentUser()).getOpenId(), sdf.format(new Date()));
                    if (!fyUserList.isEmpty()) {
                        log.info("本次获取子级用户数：{}", fyUserList.size());
                        // 获取本次新增子级用户数
                        int count = redPackInviteHelpService.addInviteHelp(fyUserList, redPackTask);
                        if (count > 0) {
                            redPackTask.setTaskStatus(2);
                        }else {
                            redPackTask.setTaskStatus(0);
                        }
                    }else {
                        redPackTask.setTaskStatus(0);
                    }
                    redPackTask.setUserTaskId(redPackUserTask.getId());
                }else { //广告任务
                    // 获取用户当天任务完成次数
                    long count = redPackUserTaskService.getTodayUserTaskList(redPackTask.getId());
                    RedPackUser redPackUser = redPackUserService.getRedPackUser(UserContext.getCurrentId());
                    if (0 != redPackTask.getEverydayCount() && count >= redPackTask.getEverydayCount()) {
                        redPackTask.setTaskStatus(1);
                    }else {
                        redPackTask.setTaskStatus(redPackUserTask.getStatus());
                    }

                    /*if (null != redPackUser && redPackUser.getIsVip() == 1) {
                        if (0 != redPackTask.getVipCount() && count >= redPackTask.getVipCount()) {
                            redPackTask.setTaskStatus(1);
                        }else {
                            redPackTask.setTaskStatus(redPackUserTask.getStatus());
                        }
                    }else {
                        if (0 != redPackTask.getEverydayCount() && count >= redPackTask.getEverydayCount()) {
                            redPackTask.setTaskStatus(1);
                        }else {
                            redPackTask.setTaskStatus(redPackUserTask.getStatus());
                        }
                    }*/
                    redPackTask.setUserTaskId(redPackUserTask.getId());
                }
            });
        }
        log.info("获取红包广场任务列表END");
        return redPackTaskList;
    }

    /**
     * 添加任务
     * @param redPackTask
     */
    @Override
    public void addRedPackTask (RedPackTask redPackTask) {
        redPackTask.setId(SnowFlake.getIdStr());
        redPackTask.setStatus(getTaskStatus(redPackTask.getStartTime(), redPackTask.getEndTime()));
        this.save(redPackTask);
    }

    /**
     * @return 任务状态
     * @see PromotionsStatusEnum
     */
    public String getTaskStatus(Date startTime, Date endTime) {
        if (endTime == null) {
            return startTime != null ? PromotionsStatusEnum.START.name() : PromotionsStatusEnum.CLOSE.name();
        }
        Date now = new Date();
        if (now.before(startTime)) {
            return PromotionsStatusEnum.NEW.name();
        } else if (endTime.before(now)) {
            return PromotionsStatusEnum.END.name();
        } else if (now.before(endTime)) {
            return PromotionsStatusEnum.START.name();
        }
        return PromotionsStatusEnum.CLOSE.name();
    }

    /**
     * 修改红包任务
     * @param redPackTask
     */
    @Override
    public void updateRedPackTask (RedPackTask redPackTask) {
        if (null == redPackTask || StringUtils.isEmpty(redPackTask.getId())) {
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }
        RedPackTask rpt = this.getById(redPackTask.getId());
        if (null == rpt) {
            throw new ServiceException("红包任务不存在");
        }
        redPackTask.setStatus(getTaskStatus(redPackTask.getStartTime(), redPackTask.getEndTime()));
        this.updateById(redPackTask);
    }

    /**
     * 删除任务
     * @param id
     */
    @Override
    public void deleteRedPackTask (String id) {
        if (StringUtils.isEmpty(id)) {
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }
        RedPackTask rpt = this.getById(id);
        if (null == rpt) {
            throw new ServiceException("红包任务不存在");
        }
        LambdaUpdateWrapper<RedPackTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(RedPackTask::getId, id);
        updateWrapper.set(RedPackTask::getDeleteFlag, true);
        this.update(updateWrapper);
    }


    /**
     * 关闭任务
     * @param id
     */
    @Override
    public void closeTask (String id) {
        if (StringUtils.isEmpty(id)) {
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }
        RedPackTask rpt = this.getById(id);
        if (null == rpt) {
            throw new ServiceException("红包任务不存在");
        }
        LambdaUpdateWrapper<RedPackTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(RedPackTask::getStartTime, null);
        updateWrapper.set(RedPackTask::getEndTime, null);
        updateWrapper.set(RedPackTask::getStatus, PromotionsStatusEnum.CLOSE.name());
        updateWrapper.eq(RedPackTask::getId, id);
        this.update(updateWrapper);
    }


    /**
     * 获取广告商品
     * @return
     */
    @Override
    public String getAdvertGoods (String taskId) {
        if (StringUtils.isNotEmpty(taskId)) {
            RedPackTask redPackTask = this.getById(taskId);
            if (null != redPackTask && redPackTask.getIsVipTask() == 1) {
                RedPackUser redPackUser = redPackUserService.getRedPackUser(UserContext.getCurrentId());
                if (redPackUser.getIsVip() == 0) {
                    throw new ServiceException("您不是飞语SVIP用户,请先开通");
                }
            }
        }
        List<Goods> goodsList = goodsAuthClient.getListByAuthSpace("GG");
        if (!goodsList.isEmpty()) {
            List<String> goodsIdList = goodsList.stream().map(Goods::getId).toList();
            int randomIndex = (int)(Math.random() * goodsIdList.size());
            return goodsIdList.get(randomIndex);
        }

        throw new ServiceException("暂无广告");
    }

}
